package core;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

import model.algoresult.redlightdelay;
import model.collect.PhaseInfo;
import model.collect.queueLenData;
import model.tobj.intersectionObj;
import model.tobj.lanesectionOBJ;
import model.tobj.lineData;
import model.tobj.pedAndPhase;
import model.tobj.queueLenStandard;
import model.tobj.stationData;

import oracle.net.aso.h;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import protocol.iec104.IEC104SendCommand;

import socket.FunccodeServersocket;
import task.iec104.IEC104SendWorker;

import config.appconfig;
import core.scheduledtask.getDBDataTask;
import core.scheduledtask.getFBDataTask;
import core.scheduledtask.getPassengersTask;
import core.scheduledtask.ontimeMSGTask;
import core.upintf.DM2Client;
import core.upintf.DM2ClientInfo;
import core.upintf.DMClient;
import core.upintf.IPAndPort;
import core.upintf.UpInterface;
import dbop.DBConnectionTester;
import dbop.DBManager;

public class IEC104Server{

	/**
	 * 算法分触发型和定时计算型
	 * 
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
				
		configLog4j();
		initRunParam();
		logger.info("init finish");
		try {
			initserver();
			startworker();
			//initintersectionObjs();
			//initProcessThreads();
			
			//initDMClient();
			
			//tmZZ.schedule(new getDBDataTask(), 10,10000);
			initYXYCdata();
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void initYXYCdata(){
		for(int i=0;i<50000;i++){
			yxdata.put(String.valueOf(i), String.valueOf(i%2));
		}
		for (int j=0;j<1000;j++){
			ycdata.put(String.valueOf(j+11781), String.valueOf(j));
		}
	}
	public static Map<String, String> yxdata= new HashMap<String, String>();
	public static Map<String, String> ycdata= new HashMap<String, String>();
	public static Map<String, String> yxFBdata= new HashMap<String, String>();
	public static Timer tmFB=new Timer();
	public static Timer tmZZ=new Timer();;
	
	
	private static Logger logger = Logger.getLogger(IEC104Server.class);
	public static int algotype;//
	public static String[] algolines;
	
	private static FunccodeServersocket server;
	private static void initserver(){
		server= new FunccodeServersocket(2404);
		server.run();
	}
	public static IEC104SendWorker worker=new IEC104SendWorker();
	private static void startworker(){
		worker.start();
	}
	
	
	private static UpInterface[] upInterface;
	
	public static Map<String, ProcessThread> processThreads=new HashMap<String, ProcessThread>();
	public static ProcessThread  getProcThread(String ip){
		ProcessThread thd= processThreads.get(ip);
		if (thd ==null){
			thd=new ProcessThread(ip);
			thd.start();
			processThreads.put(ip, thd);
			return thd;
		}
		return thd;
		
	}
	
	private static void configLog4j() {
		PropertyConfigurator.configure(new File(".").getAbsolutePath()
				+ File.separator + "config" + File.separator
				+ "log4j.properties");
    }
	private static void initRunParam(){
		 IEC104Server.algotype= appconfig.getIntProp("algo.algotype");
		 IEC104Server.algolines=appconfig.getStrProp("algo.algolines").split(",");
	}

	public static UpInterface getUpInterface() {
		return upInterface[0];
	}
	
	private static void initProcessThreads(){
		String msgs= appconfig.getStrProp("algo.msgtype");
		String[] msgtypes= msgs.split(",");
		for (int i=0;i<msgtypes.length;i++){
			ProcessThread thd= new ProcessThread(msgtypes[i]);
			thd.start();
			processThreads.put(msgtypes[i], thd);
		}
		
		
	}
	private static void initDMClient() throws Exception{
		if (true){
			int dmcount = appconfig.getIntProp("DM.count");
			upInterface = new UpInterface[dmcount];
			for (int i = 0;i<dmcount;i++){
				int version = appconfig.getIntProp("DM"+(i+1)+".version");
				int connectCount = appconfig.getIntProp("DM"+(i+1)+".servercount");
				
				if (version == 1){
					if (connectCount != 1)
						throw new IllegalArgumentException("DM 1 can only has one connection");
					String host = appconfig.getStrProp("DM"+(i+1)+".server1.host");
					int port = appconfig.getIntProp("DM"+(i+1)+".server1.port");
					int retrytime = appconfig.getIntProp("DM"+(i+1)+".server1.RetryMills");
					upInterface[i] = new DMClient(host,port,retrytime);
					
				}
				else if (version == 2){
					IPAndPort[] ports = new IPAndPort[connectCount];
					for (int j = 0;j<ports.length;j++){
						String ip = appconfig.getStrProp("DM"+(i+1)+".server"+(j+1)+".host");
						int port = appconfig.getIntProp("DM"+(i+1)+".server"+(j+1)+".port");
						int retry = appconfig.getIntProp("DM"+(i+1)+".server"+(j+1)+".port");
						ports[j] = new IPAndPort(ip,port,retry);
					}
					String userid = appconfig.getStrProp("DM"+(i+1)+".user");
					String pwd = appconfig.getStrProp("DM"+(i+1)+".pwd");
					String type = appconfig.getStrProp("DM"+(i+1)+".type");
					boolean sendToComm = Boolean.parseBoolean(appconfig.getStrProp("DM"+(i+1)+".send"));
					DM2ClientInfo info = new DM2ClientInfo(userid,pwd,type,sendToComm,ports);
					upInterface[i] = new DM2Client(info);  //use ssmq version 2
				}
				else
					throw new IllegalArgumentException(
					"current DMVersion is only 1 or 2");
				
				
			}
		}
		for (UpInterface up: upInterface)
			up.run();
	}
	private static void initintersectionObjs() throws SQLException {

		Connection conn = null;
		try {
			conn = DBManager.generateDBConn("DB"); //
		} catch (SQLException e) {
			DBConnectionTester.dbOK = false;
			logger.fatal("connect database error", e);
			logger.info("try read from local files");
		}
		if (conn!=null){
			Statement stmt = conn.createStatement();
			String sql= " select  * from devinter_rl  ";
			
			boolean result = stmt.execute(sql );
			if (result) {
				ResultSet res = stmt.getResultSet();
				while (res.next()) {
					
					String id = res.getString("intersectionid");
					//String name = res.getString("intersectionname");
					String devid = res.getString("deviceid");
					
					
					intersectionObj data= new intersectionObj(id,devid);
					
				}
				res.close();
			}
			stmt.close();
		}
		conn.close();
	}
}
